#!/usr/local/bin/perl

use strict;

use Getopt::Long;
use CompBlastMany;
use Bio::SeqIO;
use Error qw(:try);
use Mail::Send;

my $file = "";
my $cutoff = 70;
my @keywords = ();
my $hits = 4;
my $email = "";

my $result = GetOptions("file|f=s" => \$file,
			"cutoff|c=i" => \$cutoff,
			"hits|h=i" => \$hits,
			"email|e=s" => \$email,
			"keywords|k=s" => \@keywords);
my $e = 0;
if($file eq ""){
	print "Please specifiy a file name\n";
	$e = 1;
}

if($#keywords == -1){
	print "Please specify some keywords\n";
	$e = 1;
}

if($e == 1){
	print "\n";
	PrintUsage();
	exit;
}

my $p = "";
$p = "es" if ($hits > 1);

my @keys = ();

foreach(@keywords){
	my @key = split /,/,$_;
	push @keys, [ @key ];
}

#print "File: $file\n";
#print "Cutoff: $cutoff\n";
print "Keywords: ";
my $strkeys = "";
for(my $ib = 0; $ib <= $#keys; $ib++){
	my @tmp = @{$keys[$ib]};
	$strkeys .= "(" if ($#tmp > 0);
	for(my $ia = 0; $ia <= $#tmp;$ia++){
		$strkeys .= $tmp[$ia];
		$strkeys .= " OR " if($ia + 1 == $#tmp);
	}
	$strkeys .= ")" if ($#tmp > 0);
	$strkeys .= " AND " if($ib + 1 == $#keys);
}

print $strkeys;

print "Email will be sent to $email\n\n" unless ($email eq "");

my $comparer = new CompBlastMany();

$comparer->SetHits($hits);

try {
	$comparer->CheckFile($file,@keys);
} catch Bio::Root::Exception with {
	shift;
	print "Error opening file!\n";
	exit;
}; 

my @data = $comparer->GetData();

my $count = 0;
my $out = "\n";
for(my $i = $#data; $i > -1;$i--){
	if(($data[$i]->[1] < $cutoff ) && ( $data[$i]->[1] != -1)){
		$out .= "\nPossibly contaminated sequences:\n" if($count == 0);
		$out .= 100-$data[$i]->[1] . "\% - " . $data[$i]->[0] . "\n";
		$count++;
	}
}

my $i = $#data;
while($i > -1 && $data[$i]->[1] == -1){
	$out .= "\nThe following did not retrieve any results:\n" if($i == $#data);
	$out .= $data[$i]->[0] . "\n";
	$i--;
	$count++;
}

if($count > 0){
	print "$out";
} else {
	print "\n\nNo sequences appear to be contaminated!\n";
}

SendMail($email,$file,$strkeys,$out) if ($email ne  "");

sub PrintUsage {
	print "Sequence proofer\n";
	print "\nSwitches:\n";
	print "\t--file|-f\tFile name\n";
	print "\t--keywords|-k\tKeywords: Can have multiple ones and each one can \n\t\t\tbe comma deliminated\n"; 
	print "\t--hits|-h\t[OPTIONAL] Number of hits to check - default is 4\n";
}

sub SendMail {
	my ($email,$filename,$keywords,$seqs) = @_;
	print "\nSending mail to $email\n";
	my $msg = new Mail::Send;
	$msg->to($email);
	$msg->subject('Verification of sequences in '.$filename);
	
	my $fh = $msg->open;
	print $fh "The following were searched for in the description after blasting the sequences:\n\t$keywords\n\n";
	print $fh "The following sequences are possibly contaminated:\n$seqs\n";
	$fh->close;
}
